import { BadRequestException, Injectable } from '@nestjs/common';
import { Repository } from 'typeorm';
import { InjectRepository } from '@nestjs/typeorm';

import { Post } from './entities/post.entity';
import { CreatePostDto } from './dto/create-post.dto';
import { UpdatePostDto } from './dto/update-post.dto';

@Injectable()
export class PostService {
  constructor(
    @InjectRepository(Post)
    private readonly postRepository: Repository<Post>,
  ) {}

  async create(createPostDto: CreatePostDto) {
    const { title } = createPostDto;

    const doc = await this.postRepository.findOne({ where: { title } });
    if (doc) {
      throw new BadRequestException('文章已存在');
    }

    const post = new Post();
    post.title = createPostDto.title;
    post.content = createPostDto.content;
    post.author = 'admin';

    return this.postRepository.save(post);
  }

  async findAll(page: number = 1, pageSize: number = 10) {
    const [posts, totalCount] = await this.postRepository.findAndCount({
      skip: (page - 1) * pageSize, // 分页偏移量
      take: pageSize, // 每页显示的记录数
      order: { create_time: 'DESC' },
    });

    return {
      list: posts,
      count: totalCount,
      totalPages: Math.ceil(totalCount / pageSize), // 计算总页数
      currentPage: page, // 当前页
    };
  }

  findOne(id: number) {
    return this.postRepository.findOne({ where: { id } });
  }

  async update(id: number, updatePostDto: UpdatePostDto) {
    const existPost = await this.postRepository.findOne({ where: { id } });
    if (!existPost) {
      throw new BadRequestException(`id为${id}的文章不存在`);
    }
    const updatePost = this.postRepository.merge(existPost, updatePostDto);
    return this.postRepository.save(updatePost);
  }

  async remove(id: number) {
    const existPost = await this.postRepository.findOne({ where: { id } });
    if (!existPost) {
      throw new BadRequestException(`id为${id}的文章不存在`);
    }
    return this.postRepository.remove(existPost);
  }
}
